import OSS from 'ali-oss'
import dayjs from 'dayjs'
import { getOssToken } from '@/apis/common/oss'
import html2Canvas from 'html2canvas'
import { ref, reactive } from 'vue'
const tokenData = reactive({
  region: '',
  accessKeyId: '',
  accessKeySecret: '',
  stsToken: '',
  bucket: '',
  secure: true,
  expiration: 0
})

// 题目转为图片
export const transformImg = async el => {
  if (!el) return
  const canvas = await html2Canvas(el, {
    width: el.width,
    allowTaint: false,
    useCORS: true,
    scale: 1
  })
  const blob = await new Promise(resolve => {
    canvas.toBlob(resolve, 'image/jpeg', 1.0)
  })
  const file = new File([blob], 'question.jpg', {
    type: 'image/jpeg'
  })
  return file
}

// 获取上传token
export const getToken = async () => {
  if (tokenData.expiration && Date.now() / 1000 < tokenData.expiration) return
  const token = await getOssToken()
  if (token.code == 10000) {
    tokenData.region = token.data.region
    tokenData.accessKeyId = token.data.AccessKeyId
    tokenData.accessKeySecret = token.data.AccessKeySecret
    tokenData.stsToken = token.data.SecurityToken
    tokenData.bucket = token.data.bucket
    tokenData.secure = true
    tokenData.expiration = token.data.Expiration
  }
}

export const uploadImg = async file => {
  const client = new OSS(tokenData)
  const Filepath =
    '/teacher/search/question_' + dayjs().format('YYYYMMDD-HH:mm:ss') + '.jpg'
  const headers = {
    'x-oss-object-acl': 'public-read'
  }
  const result = await client.put(Filepath, file, { headers })
  return result
}
